var expenseGrid = {
    listObj: null,
    plannedListObj: null,
    
    getExpensesToJsonJqGrid: function(options)
    {
        this.listObj = jQuery("#list").jqGrid({ 
            url: options.url, 
            //height: "auto", 
            height: 350,
            datatype: "local", //or json - load data via server
            gridview: true,
            sortname: 'e.date', 
            viewrecords: true, 
            rowNum: -1,
            editurl: options.url_edit,
            sortorder: "desc",
            colNames:['Id', 'Kategoria', 'Cena', 'Komentarz', 'Data', 'Akcje'],
            colModel:[ 
                {name:'id', index:'e.id', hidden: true, width:55}, 
                {name:'name', index:'c.name', width:200, editable:true, edittype:"select", editrules: { required: true }}, 
                {name:'price', index:'e.price', width:100, editable:true, sorttype:'integer', searchoptions:{sopt:['eq','ne','le','lt','gt','ge']}}, 
                {name:'comment', index:'e.comment', width:265, editable:true, sorttype:'string', searchoptions:{sopt:['eq','ne','le','lt','gt','ge']}}, 
                {name:'date', index:'e.date', width:110, editable:true, sorttype:'string', searchoptions:{sopt:['eq']}, editoptions:{
                    dataInit:function(el){ 
                        $(el).datetimepicker({"format": "dd.mm.yyyy", "pickerPosition": "bottom-left", "minView": "month"});
                    }
                }}, 
                {name:'act',index:'act', width:100,sortable:false}
            ],
            gridComplete: function() { 
                var ids = jQuery("#list").jqGrid('getDataIDs'); 
                for (var i=0;i < ids.length;i++) { 
                    var cl = ids[i]; 
                    var btnEdit, btnCancle, btnDel, btnSave = '';
                    btnEdit   = "<span class=\"glyphicon glyphicon-edit grid-icon btn-edit\" title=\"Edit\" onclick=\"jQuery('#list').editRow('" + cl + "');\"></span>"; 
                    btnSave   = "<span class=\"glyphicon glyphicon-floppy-save grid-icon btn-save\" title=\"Save\" onclick=\"jQuery('#list').saveRow('" + cl + "');\"></span>"; 
                    btnCancle = "<span class=\"glyphicon glyphicon-floppy-remove grid-icon btn-cancle\" title=\"Cancel\" onclick=\"jQuery('#list').restoreRow('" + cl + "');\"></span>"; 
                    btnDel    = "<span class=\"glyphicon glyphicon-remove-circle grid-icon del-row\" title=\"Delete\" date=\"" + cl + "\"></span>";
                    jQuery("#list").jqGrid('setRowData',ids[i],{act: btnEdit + btnSave + btnCancle + btnDel}); 
                }
                $('.btn-save').hide();
                $('.btn-cancle').hide();
            },
            
            loadComplete: function() {
                $("#list").setColProp('name', { editoptions: { value: options.categoriesForGrid} });
            }
        }); 
        
        //load data to grid from options
        for (var i=0; i<=options.expensesListData.length; i++) {
            jQuery("#list").jqGrid('addRowData', i+1, options.expensesListData[i]);
        }
        //change to load data via the server
        this.listObj.jqGrid('setGridParam', {datatype:'json'});
        
        jQuery("#list").jqGrid('navGrid' ,'#pager' ,{edit:false, add:false, del:false});
        jQuery("#list").jqGrid('filterToolbar',{searchOperators : true});
        
        $('body').on('click', '.btn-edit', function() {
            $(this).parent('td').find('.btn-edit').hide();
            $(this).parent('td').find('.del-row').hide();
            $(this).parent('td').find('.btn-save').show();
            $(this).parent('td').find('.btn-cancle').show();       
        });
        
        $('body').on('click', '.btn-cancle', function() {
            showIcon(this);
        });
        
        $('body').on('click', '.btn-save', function() {
            showIcon(this);
        });
        
        
        function showIcon(e) {
            $(e).parent('td').find('.btn-save').hide();
            $(e).parent('td').find('.btn-cancle').hide();
            $(e).parent('td').find('.btn-edit').show();
            $(e).parent('td').find('.del-row').show();
        }
        
        $('body').on('click', '.del-row', function() {
            if (confirm('Are you sure you want to delete this expense?')) {
                var id = $(this).attr('date');
                $.ajax({
                    url: options.url_del, 
                    async: false,
                    type: 'post',
                    data: { id: id},
                    success: function(data) 
                     {
                       if (data === 'TRUE') {
                            $('#list').trigger("reloadGrid");                 
                       }
                     }
                });
            }
        });
        
        $('body').on('focus', '#gs_date', function() {
             $(this).datetimepicker({
                 "format": "dd.mm.yyyy", 
                 "pickerPosition": "bottom-left", 
                 "minView": "month", 
                 "startView": "month"
                 }).on('changeDay', function(ev){
                    var day   = ev.date.getDay(); 
                    var month = ev.date.getMonth() + 1; 
                    var year  = ev.date.getFullYear(); 
                    if (month < 10) {
                        month = '0' + month;
                    }
                    if (day < 10) {
                        day = '0' + day;
                    }

                    $('#list').jqGrid('setGridParam',{ postData:{ 'e.date': day + '.' + month + '.' + year }, search:true });
                    $('#list').trigger("reloadGrid");
                });
        });
        
    },
    
    getPlannedExpensesToJsonJqGrid: function(options)
    {
        var date = $('#select-month').val();
        if (!date) {
            date = moment().format('MM.YYYY');
        }
        
        this.plannedListObj = jQuery("#list_planned_expenses").jqGrid({ 
            url: options.url + '?date=' + date, 
            height: "auto", 
            datatype: "local", 
            colNames:['Id', 'Kategoria', 'Cena', 'Nazwa/Komentarz', 'Termin płatności', '', 'Akcje'],
            colModel:[ 
                {name:'id', hidden: true, index:'pe.id', width:55}, 
                {name:'category', index:'c.name', width:200, editable:true, edittype:"select", editrules: { required: true }}, 
                {name:'amount', index:'pe.amount', width:100, editable:true, sorttype:'integer', searchoptions:{sopt:['eq','ne','le','lt','gt','ge']}}, 
                {name:'name', index:'pe.name', width:265, editable:true, sorttype:'string', searchoptions:{sopt:['eq','ne','le','lt','gt','ge']}}, 
                {name:'date_expired', index:'pe.date_expired', width:110, editable:true, sorttype:'string', searchoptions:{sopt:['eq']}, editoptions:{
                    dataInit:function(el){ 
                        $(el).datetimepicker({"format": "dd.mm.yyyy", "pickerPosition": "bottom-left", "minView": "month"});
                    }
                }}, 
                {name:'class',index:'class', width: 20, sortable: false, hidden: true},
                {name:'act',index:'act', width:100,sortable:false}
            ],
            gridComplete: function() { 
                var ids = jQuery("#list_planned_expenses").jqGrid('getDataIDs'); 
                for (var i=0;i < ids.length;i++) { 
                    var cl = ids[i]; 
                    var btnEdit, btnCancle, btnDel, btnSave, btnMovie = '';
                    btnEdit   = "<span class=\"glyphicon glyphicon-edit grid-icon btn-edit2\" title=\"Edit\" onclick=\"jQuery('#list_planned_expenses').editRow('" + cl + "');\"></span>"; 
                    btnSave   = "<span class=\"glyphicon glyphicon-floppy-save grid-icon btn-save2\" title=\"Save\" onclick=\"jQuery('#list_planned_expenses').saveRow('" + cl + "');\"></span>"; 
                    btnCancle = "<span class=\"glyphicon glyphicon-floppy-remove grid-icon btn-cancle2\" title=\"Cancel\" onclick=\"jQuery('#list_planned_expenses').restoreRow('" + cl + "');\"></span>"; 
                    btnDel    = "<span class=\"glyphicon glyphicon-remove-circle grid-icon del-row2\" title=\"Delete\" date=\"" + cl + "\"></span>";
                    btnMovie  = "<span class=\"glyphicon glyphicon-plus grid-icon btn-movie\" title=\"Movie to expense\" date=\"" + cl + "\"></span>";
                    jQuery("#list_planned_expenses").jqGrid('setRowData',ids[i],{act: btnEdit + btnSave + btnCancle + btnDel + btnMovie});                                           
                }
                
                var tableRow = $("td").filter(function() {
                    return $(this).text() == "redGridRow";
                }).closest("tr").css('background', '#F58EA3');

                var tableRow = $("td").filter(function() {
                    return $(this).text() == "greenGridRow";
                }).closest("tr");
                tableRow.css('background', '#9CE892');
                tableRow.find('.btn-movie').hide();
                tableRow.find('.btn-edit2').hide();
                
                    
                $('.btn-save2').hide();
                $('.btn-cancle2').hide();
            },
            
            gridview: true,
            sortname: 'e.date_created', 
            viewrecords: true, 
            editurl: options.url_edit,
            sortorder: "desc",
            loadComplete: function() {
                $("#list_planned_expenses").setColProp('category', { editoptions: { value: options.categoriesForGrid} });
            }
        }); 

        //load data to grid from options
        for (var i=0; i<=options.plannedExpensesListData.length; i++) {
            this.plannedListObj.jqGrid('addRowData', i+1, options.plannedExpensesListData[i]);
        }
        
        //change to load data via the server
        this.plannedListObj.jqGrid('setGridParam', {datatype:'json'});
        
        $('body').on('click', '.btn-edit2', function() {
            $(this).parent('td').find('.btn-edit2').hide();
            $(this).parent('td').find('.del-row2').hide();
            $(this).parent('td').find('.btn-movie').hide();
            $(this).parent('td').find('.btn-save2').show();
            $(this).parent('td').find('.btn-cancle2').show();       
        });
        
        $('body').on('click', '.btn-save2', function() {
            showIcon(this);
        });
        
        $('body').on('click', '.btn-cancle2', function() {
            showIcon(this);
        });
        
        $('body').on('click', '.btn-movie', function() {
            if (confirm('Are you sure you want to movie this planned expense to expenses?')) {
                var id = $(this).attr('date');
                $.ajax({
                    url: options.url_movie_to_expense, 
                    async: false,
                    type: 'post',
                    data: { id: id},
                    success: function(data) 
                     {
                        $('#list_planned_expenses').trigger("reloadGrid");  
                        $('#list').trigger("reloadGrid");  
                     }
                });
            }
        });
        
        function showIcon(e) {
            $(e).parent('td').find('.btn-save2').hide();
            $(e).parent('td').find('.btn-cancle2').hide();
            $(e).parent('td').find('.btn-edit2').show();
            $(e).parent('td').find('.del-row2').show();
            $(e).parent('td').find('.btn-movie').show();
        }
        
        $('body').on('click', '.del-row2', function() {
            if (confirm('Are you sure you want to delete this planned expense?')) {
                var id = $(this).attr('date');
                $.ajax({
                    url: options.url_del, 
                    async: false,
                    type: 'post',
                    data: { id: id},
                    success: function(data) 
                     {
                        $('#list_planned_expenses').trigger("reloadGrid");  
                     }
                });
            }
        });
        
        $('body').on('focus', '#gs_date_created', function() {
             $(this).datetimepicker({
                 "format": "dd.mm.yyyy", 
                 "pickerPosition": "bottom-left", 
                 "minView": "month", 
                 "startView": "month"
                 }).on('changeDay', function(ev){
                    var day   = ev.date.getDay(); 
                    var month = ev.date.getMonth() + 1; 
                    var year  = ev.date.getFullYear(); 
                    if (month < 10) {
                        month = '0' + month;
                    }
                    if (day < 10) {
                        day = '0' + day;
                    }

                    $('#list_planned_expenses').jqGrid('setGridParam',{ postData:{ 'e.date_created': day + '.' + month + '.' + year }, search:true });
                    $('#list_planned_expenses').trigger("reloadGrid");
                });
        });
        
        $('body').on('focus', '#planned_expense_date_expired', function() {
             $(this).datetimepicker({"format": "dd.mm.yyyy", "pickerPosition": "bottom-left", "minView": "month"});
        });
    }
}
